<template>
  <div>
    <common-head :title="title" />
    <div class="wrap2">
      <!-- 轮播 -->
      <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
        <van-swipe-item v-for="img in pics" :key="img.id">
          <img :src="img.pic" alt="">
        </van-swipe-item>
      </van-swipe>
      <!-- 、轮播 -->
      <h3>{{ basicInfo.name }}</h3>
      <div class="content" v-html="content"></div>
    </div>
    <!-- 商品规格 -->
    <van-popup v-model="show" position="bottom" round closeable :style="{ height: '30%' }">
      <div>
        <van-card
          :num="sku.num"
          :price="sku.minPrice"
          :title="sku.name"
          :thumb="sku.pic"
        >
          <template #footer>
            <van-stepper v-model="sku.num" />
            <van-button @click="addCart" type="danger" size="large">确定</van-button>
          </template>
        </van-card>
      </div>
    </van-popup>
    <!-- /商品规格 -->
    <!-- 提交购物车 -->
    <van-goods-action>
        <van-goods-action-icon icon="home-o" text="首页" @click="$router.push('/home')" />
        <van-goods-action-icon icon="cart-o" :badge="$store.state.cart.items.length||''" text="购物车" @click="$router.push('/cart')" />
        <van-goods-action-button
          type="danger"
          text="加入购物车"
          @click="showSku"
        />
      </van-goods-action>
      <!-- /提交购物车 -->
  </div>
</template>

<script>
import CommonHead from 'components/CommonHead'
import { fetchItemDetail, addCart } from 'api'
import { getToken } from 'utils'
import { Toast } from 'vant'
export default {
  name: 'detail',
  data () {
    return {
      title: '',
      basicInfo: {},
      pics: [],
      content: '',
      show: false,
      sku: {}
    }
  },
  created () {
    this.fetchItemDetail()
  },
  methods: {
    addCart (id, num) {
      id = this.$route.query.id
      num = this.sku.num
      addCart({
        goodsId: id,
        number: num,
        token: getToken()
      }).then(res => {
        console.log(res)
        if (res.data.code === 0) {
          Toast.success('加入成功，请前往购买')
          this.$store.commit('cart/set_items', res.data.data.items)
        }
      })
    },
    showSku () {
      this.show = true
    },
    fetchItemDetail () {
      fetchItemDetail(this.$route.query.id).then(res => {
        console.log(res)
        if (res.data.code === 0) {
          this.basicInfo = res.data.data.basicInfo
          this.pics = res.data.data.pics
          this.title = this.basicInfo.name
          this.sku = {
            ...this.sku,
            ...res.data.data.basicInfo
          }
          this.content = res.data.data.content.replace(/<img/gi, '<img style="display:block;width: 100%"')
        }
      })
    }
  },
  components: {
    CommonHead
  }
}
</script>

<style lang="scss" scoped>
.wrap2{
  padding-top: 46px;
  padding-bottom: 50px;
  .my-swipe{
    img{
      width: 100%;
    }
  }
}
</style>
